package com.demo.exception;

import com.demo.dto.GeneralResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * 全局Controller层异常处理类
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionResolver {

    /**
     * 校验单个对象不通过异常处理
     * @param exception
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public GeneralResult validateException(MethodArgumentNotValidException exception) {
        BindingResult bindingResult = exception.getBindingResult();
        FieldError fieldError = bindingResult.getFieldError();
        return GeneralResult.error(fieldError.getDefaultMessage());
    }

    /**
     * 校验集合数据不通过异常处理
     * @param exception
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public GeneralResult constraintViolationException(ConstraintViolationException exception) {
        return GeneralResult.error(exception.getMessage());
    }
}
